package com.zh.filter;

import com.alibaba.fastjson.JSON;
import com.zh.common.BaseContext;
import com.zh.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*",filterName = "LoginCheckFilter")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();
        //放行uri:
        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                //访问入口
                "/admin",
                "/user",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",

        };
        //1.是否需要拦截:
        if (check(uris, uri)) {
//            log.info("必须资源直接放行,{}", uri);
            filterChain.doFilter(request, response);
            return;
        }

        //2-1.判断emp是否已登录:
        Long employee = (Long) request.getSession().getAttribute("employee");
        if (employee != null) {
            log.info("已登录，直接放行 id：{}", employee);
            BaseContext.setCurrentId(employee);//id存入线程
            filterChain.doFilter(request, response);
            return;
        }
        //2-2.判断user是否已登录:
        Long user = (Long) request.getSession().getAttribute("user");
        if (user != null) {
            log.info("已登录，直接放行 id：{}", user);
            BaseContext.setCurrentId(user);//id存入线程
            filterChain.doFilter(request, response);
            return;
        }

        //3. 拦截
        log.info("未登录,拦截到请求:{}", uri);
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }

    public boolean check(String[] uris, String requestUri) {
        for (String uri : uris) {
            if (PATH_MATCHER.match(uri, requestUri)) {
                return true;
            }
        }
        return false;
    }
}
